package com.gxa.community.admin.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.community.admin.mapper.order.OrderInfoMapper;
import com.gxa.community.admin.mapper.user.UserMapper;
import com.gxa.community.admin.service.user.UserService;
import com.gxa.community.core.pojo.domain.OrderInfo;
import com.gxa.community.core.pojo.domain.UserInfo;
import com.gxa.community.core.pojo.domain.UserShippingAddress;
import com.gxa.community.core.pojo.dto.userdto.UserDto;
import com.gxa.community.core.pojo.vo.admin.user.UserVo;
import com.gxa.community.core.pojo.vo.admin.user.expend.OrderInfoE;
import com.gxa.community.core.pojo.vo.admin.user.expend.UserInfoE;
import com.gxa.community.core.pojo.vo.admin.user.expend.UserShippingAddressE;
import com.gxa.community.core.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service("adminUser")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    RedisTemplate<String ,Object> redisTemplate;

    /**
     * 查询用户信息
     *
     * @param userDto
     * @return
     */
    @Override
    public R queryUserInfo(UserDto userDto,
                           int page,
                           int size) {
        Page<UserInfo> page1 = new Page<>(page, size);

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();

        if (userDto.getNickName() != null && !"".equals(userDto.getNickName()))
            userInfoQueryWrapper.eq("nick_name", userDto.getNickName());

        if (userDto.getCardId() != null && !"".equals(userDto.getCardId()))
            userInfoQueryWrapper.eq("card_id", userDto.getCardId());

        if (userDto.getPhone() != null && !"".equals(userDto.getPhone()))
            userInfoQueryWrapper.eq("phone", userDto.getPhone());

        if (userDto.getUserId() != null && !"".equals(userDto.getUserId()))
            userInfoQueryWrapper.eq("user_id", userDto.getUserId());

        if (userDto.getSex() != null)
            userInfoQueryWrapper.eq("sex", userDto.getSex());

        if (userDto.getStartTime() > 0 && userDto.getEndTime() > 0)
            userInfoQueryWrapper.between("create_time", userDto.getStartTime(), userDto.getEndTime());
        //如果有起始时间那么，结束时间为当前，只有结束时间，必须有起始时间。
        if (userDto.getStartTime() > 0)
            userInfoQueryWrapper.between("create_time", userDto.getStartTime(), System.currentTimeMillis());

        if (userDto.getStatus() != null)
            userInfoQueryWrapper.eq("status", userDto.getStatus());

        //查询所有用户
        Page<UserInfo> userInfoPage = userMapper.selectPage(page1, userInfoQueryWrapper);

        List<UserVo> userVo = new ArrayList<>();

        userInfoPage.getRecords().forEach(p -> {

            Integer orderNum = 0;
            BigDecimal amount = BigDecimal.valueOf(0.00);

            if (!ObjectUtils.isEmpty(userMapper.queryUserInfo(p.getUserId()))){
                orderNum = userMapper.queryUserInfo(p.getUserId()).getOrderNum();
                amount = userMapper.queryUserInfo(p.getUserId()).getAmount();
            }
            //查询用户标签
            List<String> strings = userMapper.queryUserTags(p.getUserId());
            //查询用户收件人信息
            List<UserShippingAddress> userShippingAddresses = userMapper.queryUserShippingAddress(p.getUserId());
            //查询订单信息
            List<OrderInfo> orderInfoList = userMapper.queryUserOrderInfo(p.getUserId());
            //将用户信息组合近vo
            userVo.add(new UserVo()
                    //用户信息
                    .setUserInfo(new UserInfoE()
                            .setUserId(p.getUserId())
                            .setCreateTime(p.getCreateTime())
                            .setNickName(p.getNickName())
                            .setPhone(p.getPhone())
                            .setSex(p.getSex())
                            .setAddress(p.getAddress())
                            .setStatus(p.getStatus()))
                    //设置个人消费金额和订单数量
                    .setOrderNum(orderNum)

                    .setAmount(amount)

                    .setTagsList(strings)
                    //收件人信息
                    .setUserShippingAddressList(userShippingAddresses.stream().map(usa -> {
                        return new UserShippingAddressE()
                                .setId(usa.getId())
                                .setPhone(usa.getPhone())
                                .setIslandName(usa.getIslandName())
                                .setName(usa.getName());
                    }).collect(Collectors.toList()))
                    //订单信息
                    .setOrderInfoList(orderInfoList.stream().map(or -> {
                        return new OrderInfoE()
                                .setId(or.getId())
                                .setCreateTime(or.getCreateTime())
                                .setPayment(or.getPayment().doubleValue())
                                .setPrice(or.getPrice().doubleValue())
                                .setNo(or.getNos())
                                .setStatus(or.getStatus());
                    }).collect(Collectors.toList())));
        });

        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("total",userInfoPage.getTotal());
        hashMap.put("pages",userInfoPage.getPages());
        hashMap.put("pageSize",userInfoPage.getSize());
        hashMap.put("currentPage",userInfoPage.getCurrent());
        hashMap.put("list",userVo);
        System.out.println(hashMap);
        return R.ok().put("data",hashMap);
    }

    /**
     * 批量设置用户标签
     *
     * @param userDto
     * @return
     */
    @Override
    public R addUserTags(UserDto userDto) {
        //删除所有标签
        userMapper.delUserTags(userDto);
        //重新添加标签
        int result = userMapper.addUserTags(userDto);

        return result > 0 ? R.ok("设置成功") : R.error("设置失败");
    }
}